local oo = require("SharedLibs.BaseLib")
local co = require("SharedLibs.CoroLib")

Debugger = require("SharedLibs.Debugger")

ISignal = require("SharedLibs.Signal.ISignal")
IEmitter = require("SharedLibs.Signal.IEmitter")
Signal = require("SharedLibs.Signal.Signal")

--- SignalWrapper只能传递数据，没有Emit方法直接发射数据
local SignalWrapper = oo.class("SignalWrapper");
SignalWrapper:implements(ISignal);
SignalWrapper:implements(IEmitter);

--- 注册到co里
co.SignalWrapper = SignalWrapper;

--- dataWrapper接收任意个参数(...)， 返回 (ret, ...)。
--- 返回值：第一个是false，则这个data被过滤掉。否则，将Emit(...)
function SignalWrapper:constructor(srcSignal, dataWrapper, name)
	assert(srcSignal);
	assert(dataWrapper);
	
	self._dataWrapper = dataWrapper;
	self._signal = Signal.new();
	self._srcSignal = srcSignal;
	
	self.name = name or "SignalWrapper";
end

function SignalWrapper:Emit(...)
	self._signal:Emit(...);
end

function SignalWrapper:On(handler, retDestroyer)
	self._signal:On(handler);
	 
	if self._signal:GetHandlerCount() == 1 then
		self._onSrcSignal = function(...)
			local vars = { self._dataWrapper(...) };
			local ret = table.remove(vars, 1);
			--- ret为true表示可以Emit，否则表示数据被过滤掉
			if ret then
				self._signal:Emit(table.unpack(vars));
			end
		end;
		self._srcSignal:On(self._onSrcSignal);
	end

	if retDestroyer then return function() self:Off(handler); end end
end

function SignalWrapper:Off(handler) 
	self._signal:Off(handler);

	if self._signal:GetHandlerCount() == 0 then
		self._srcSignal:Off(self._onSrcSignal);
		self._onSrcSignal = nil;
	end
end

function SignalWrapper:Clear()
	if self._signal:GetHandlerCount() == 0 then return end;
 
	self._signal:Clear();

	self._srcSignal:Off(self._onSrcSignal);
	self._onSrcSignal = nil;
end

function SignalWrapper:GetHandlerCount()
	return self._signal:GetHandlerCount();
end

function SignalWrapper:HasHandler(listener)
	return self._signal:HasHandler(listener);
end

return SignalWrapper;
